package com.bookbuf.verify.base;


import com.bookbuf.verify.VerifyCode;

/**
 * Created by robert on 15/11/6.
 */
public abstract class Verify<Callback extends IVerifyCallback> extends Chain<Verify<Callback>> implements IVerify {

	protected Callback callback;

	public Verify (Callback callback) {
		this.callback = callback;
	}

	protected abstract int verify ();


	protected boolean verifySuccess (int code) {
		return code == VerifyCode.CODE_SUCCESS;
	}

	@Override
	public void execute () {
		final int code = verify ();
		if (verifySuccess (code)) {
			/*验证通过*/
			Verify<Callback> next = getNextVerify ();
			if (next != null) {
				/*递归执行验证*/
				next.execute ();
			} else {
				/*所有的验证均通过*/
				onSuccessCallback ();
			}
		} else {
			/*验证不通过*/
			onFailedCallback (code);
		}
	}

	protected abstract void onFailedCallback (int code);

	protected void onSuccessCallback () {
		ISuccessCallback callback = getSuccessCallback ();
		if (callback != null) {
			callback.onSuccess ();
		}
	}

}
